import { Principle, LoginParams } from './src/Auth'
import Vue from 'vue'
import AuthPlugin from './src'
import store from '@/store'
import { getUserEnterprises } from '@/api/enterprise'
import { getProperties } from '@/api/properties'
import { queryPermGroupByEnt } from '@/api/perm-group'
import { init, abort } from '@/views/pages/local/sync'

Vue.use(AuthPlugin, {
  principleLoader: function (): Promise<Principle> {
    const http = Vue.prototype.$http
    const all = [http.get('/api/account/account/current'), getUserEnterprises()]
    return Promise.all(all).then(([user, enterprises]) => {
      const spaces = enterprises.map((v: any) => {
        return {
          type: 'enterprise',
          name: v.name,
          ownId: v.id
        }
      })
      spaces.push({ type: 'user', name: '我的文档', ownId: -1 })
      const storage = Vue.prototype.$storage
      const space = storage.get('space', user.id)
      const newSpace = spaces.find((v: any) => v.ownId === space?.ownId) || spaces[0]
      storage.set('space', newSpace, user.id)
      store.commit('app/setSpaces', spaces)
      store.commit('app/setCurrentSpace', newSpace)

      if (newSpace.ownId !== -1) {
        queryPermGroupByEnt(newSpace.ownId).then(data => {
          const ret = (data || []).map(v => ({ label: v.name, value: v.umask }))
          store.commit('app/setPermGroups', ret)
        })
      }

      // store.commit('app/setProperties', properties)

      setTimeout(() => {
        // 初始化同步
        init()
      }, 0)

      return {
        user: {
          username: user.name,
          cname: user.name,
          id: user.id,
          avatar: user.avatar
        },
        roles: [],
        authorities: []
      }
    })
  },
  logoutHandler: function (): Promise<string> {
    const http = Vue.prototype.$http
    localStorage.removeItem('jwt_token')
    localStorage.removeItem('token')
    return Promise.resolve('')
  },
  loginHandler: function (params: LoginParams): Promise<any> {
    const http = Vue.prototype.$http
    const data = {
      username: params.type + ':' + params.identifier,
      password: params.credential,
      grant_type: 'password',
      client_id: 'client',
      client_secret: '123456'
    }
    return http.post('/api/uaa/oauth/token', {}, { params: data })
  }
})
